package org.listener.socket;

import org.mg.engine.core.MgSession;
import org.mg.engine.core.Session;
import org.msg.commons.Logger;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Create by bo.chen in 2018/10/12 22:38
 */
public class Listener {

    /**
     *  端口
     */
    private final static int PORT = 9000;

    private static ServerSocket serverSocket;

    static {
        try {
            serverSocket = new ServerSocket(PORT);
            Logger.log("start up success.");
        } catch (IOException e) {
            throw new RuntimeException(PORT + ", No socket could be created.");
        }
    }

    public static void start() {
        try {
            while(true) {
                Socket socket = serverSocket.accept();
                Logger.log(socket.getLocalAddress() +  "  client connection success.");
                if(null != socket) {
                    new Thread(() -> {
                        Session session = new MgSession(socket);
                        ApplicationHandler.set(session);
                    }).start();
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("");
        }
    }
}
